<?php
class SsoWS_Model_UserLoginStatus extends Ext_Db_Table
{
	protected $_name = "sys_user_login_status";
	protected $_primary = "user_id";
	protected $_secuence = false;
	
	private $_token = null;
	private $_is_login = null;
	private $_user_id = null;
	
	public function getStatus( $token )
	{
		$row = $this->fetchRow( "token = '". $token . "'" );
		if( $this->validateToken( $token )) { 
			$this->_is_login = $row->is_login;
			$this->_user_id = $row->user_id;
			return $row->is_login;
		}
		return false;
	}
	
	public function getUsernameByToken ( $token )
	{
		if(!  $this->validateToken( $token )) { 
			return false;
		}
		$row = $this->getAdapter()->fetchRow( 
			$this->getAdapter()
				->select()
				->from( array( 'us' => 'sys_user' ), array( 'username' ) ) 
				->join( array( 'uls' => 'sys_user_login_status' ), 'uls.user_id = us.user_id', array('token'))
				->where( 'uls.token = ? ', $token 
			)
		);
		if( count( $row )) {
			return $row['username'];
		}
		return false;
	}
	
	public function logout( $userId )
	{
		$row = $this->fetchRow( "user_id = '". $userId . "'" );
		if( count( $row )) {
			$row->is_login = 'F';
			$row->expiration_date = Ext_Db_Date::now();
			$row->save();
			return true;
		}
		return false;
	}
	
	public function getId( $username = null )
	{
		return (int) $this->_user_id;
	}

	public function getRowByToken( $token )
	{
		if( ! $this->validateToken( $token )) { 
			return $this->createRow();
		}
		$row = $this->fetchRow( $this->select()->where( 'token = ? ', $token  ));
		if( !count( $row ))  {
			return $this->createRow();
		}
		return $row;
	}
	
	public function getRow( $id = null )
	{
		$row = $this->find( $id )->current();
		
		if( !count( $row ))  {
			
			return $this->createRow();
		}
		if( ! $this->validateToken( $row->token )) {
			$row->delete();
			return $this->createRow();
		}
		return $row;
	}
	
	public function getToken( $userId = false)
	{
		if( $userId != false ) {
			$row = $this->find( $userId )->current();
			if( count( $row )) {
				if( $this->validateToken( $row->token )) {
					$this->_token = $row->token;
					return $this->_token;
				}
			}
		}
		if( $this->_token == null ) {
			$this->_token = sha1( time() . $userId );
			
		}
		return $this->_token;
	}
	
	public function validateToken( $token ) 
	{
		
		$row = $this->fetchRow( $this->select()->where('token= ?', $token ) );
		if( count( $row )) {
			if ( $row->last_login instanceof Ext_Db_Date ){
				if( $row->expiration_date instanceof Ext_Db_Date ){
					if( $row->last_login->compare($row->expiration_date) == -1 ) {
						$this->_token = $row->token;
						return true;
					}
				} 
			} 
			$this->_token = null;
			$row->expiration_date = null;
			$row->last_login = null;
			$row->save();
		}
		$this->_token = null;
		return false;
	}
	
	public function getTimeLife()
	{
		return time() + 7200;
	}
}